﻿using System;
using System.Linq;
using System.Web.ModelBinding;
using Altairis.FluffyCloud.Data;
using Altairis.FluffyCloud.Security;

namespace Altairis.FluffyCloud.WebCore.Pages.My {

    public partial class Messages : DbPage {

        public IQueryable<Message> MessageList_GetData([RouteData]string userName) {
            // Get all messages for current user
            var q = from m in this.DbContext.Messages
                    where m.FromUserName.Equals(this.User.Identity.Name, StringComparison.CurrentCultureIgnoreCase) || m.ToUserName.Equals(this.User.Identity.Name, StringComparison.CurrentCultureIgnoreCase)
                    select m;

            if (!string.IsNullOrWhiteSpace(userName)) {
                // Filter also by second user name
                q = from m in q
                    where m.FromUserName.Equals(userName, StringComparison.CurrentCultureIgnoreCase) || m.ToUserName.Equals(userName, StringComparison.CurrentCultureIgnoreCase)
                    select m;

                // Set page title
                this.Title = "Konverzace s uživatelem " + userName.ToUpper();
                this.LiteralTitle.Text = this.Title;
            }
            return q.OrderByDescending(x => x.DateCreated);
        }

        public object[] RecipientList_GetData([RouteData]string userName) {
            var q = from u in this.DbContext.Users
                    where u.IsApproved
                    orderby u.UserName
                    select new {
                        Text = u.UserName.ToUpper() + (string.IsNullOrEmpty(u.Comment) ? "" : " (" + u.Comment.Trim() + ")"),
                        Value = u.UserName
                    };

            if (!string.IsNullOrWhiteSpace(userName)) {
                q = q.Where(x => x.Value.Equals(userName, StringComparison.CurrentCultureIgnoreCase));
                if (!q.Any()) this.Response.RedirectToRoute("MyMessages");
                this.RecipientList.Items.Clear();
            }

            return q.ToArray();
        }

        protected void ButtonSend_Click(object sender, EventArgs e) {
            if (!this.IsValid) return;

            // Get target user
            var toUserName = this.RecipientList.SelectedValue;
            var toUser = this.DbContext.Users.FirstOrDefault(x => x.UserName.Equals(toUserName));
            if (toUser == null) {
                ModelState.AddModelError("UserNotFound", string.Format("Uživatel <code>{0}</code> neexistuje", toUserName));
                return;
            }
            if (!toUser.AccessList.EvaluatePermissions(UserAclEntry.OperationSendPrivateMessage)) {
                ModelState.AddModelError("AccessDenied", string.Format("Nemáte právo posílat zprávy uživateli <code>{0}</code>", toUserName));
                return;
            }

            // Send message
            var msg = this.DbContext.Messages.Add(new Message {
                FromUserName = this.User.Identity.Name,
                ToUserName = toUserName,
                Text = this.TextTextBox.Text,
                IpAddress = this.Request.UserHostAddress
            });
            this.DbContext.SaveChanges();

            // Send e-mail notification
            if (msg.ToUser.SendNewMessagesToEmail) {
                Altairis.MailToolkit.Mailer.SendTemplatedMessage(msg.ToUser.Email, "NewPrivateMessage",
                    msg.FromUserName,   // 0
                    msg.Text);          // 1
            }

            // Redirect to self
            Response.Redirect(this.Request.Url.ToString());
        }

        protected void Page_Load(object sender, EventArgs e) {
            // Get secure feed link
            if (this.RouteData.Values["userName"] == null) {
                this.FeedLink.NavigateUrl = this.GetRouteUrl("MyMessagesFeed", new { securityCode = this.Context.GetUserData().SecurityCode });
            }
            else {
                this.FeedLink.NavigateUrl = this.GetRouteUrl("MyUserMessagesFeed", new { securityCode = this.Context.GetUserData().SecurityCode, userName = this.RouteData.Values["userName"] });
            }

            // Mark all messages as read on prerender complete
            this.PreRenderComplete += (s, a) => {
                var q = from m in this.DbContext.Messages
                        where m.ToUserName.Equals(this.User.Identity.Name) && !m.DateRead.HasValue
                        select m;
                foreach (var m in q) {
                    m.DateRead = DateTime.UtcNow;
                }
                this.DbContext.SaveChanges();
            };
        }
    }
}